"use client";


import { useState, useRef, useMemo } from "react";
import Image from "next/image";
import Link from "next/link";
import { usePathname } from "next/navigation";
import { useRouter } from "next/navigation";
import { API_CONFIG } from "../app/url";
export default function Navbar() {
  const pathname = usePathname();
  const router = useRouter();
  const [showLoginModal, setShowLoginModal] = useState(false);


  const handleClick = () => {
    localStorage.clear(); // 清除所有localStorage数据
    router.push("/");
    setTimeout(() => {
      router.push("/login");
    }, 1000);
    
  };

  const handleClick1 = () => {
    localStorage.clear(); // 清除所有localStorage数据
    router.push("/tealogin");
  };
  const handleLogout = () => {
    // 清除 localStorage 中的所有数据
    localStorage.clear();
    // 退出后重定向到首页或其他页面
    router.push("/");
  };

  // 修改导航项，使用锚点链接指向consultation-section
  const navItems = [
    { href: "/", label: "首页" },
    { href: "/training-intro", label: "培训介绍" },
    { href: "/#consultation-section", label: "我要报名" },
    { href: "/#course-section", label: "我要上课" , requiresPost: true },
    { href: "/#course-section2", label: "我要练题", requiresPost: true },
    { href: "/#course-section3", label: "我要考试", requiresPost: true },
    { href: "/xueyuanzhongxin1", label: "学员中心" },
    { href: "/teachers", label: "培训师资" },
    { href: "/certificates", label: "培训证书" },
    
    { href: "/invoice", label: "发票开具" },
    { href: "/policies", label: "政策法规库" },
  ];
  const handlePostRequest = async (apiPath: string) => {
    try {

      const user = JSON.parse(localStorage.getItem('user') || '{}');

      const response = await fetch(`${API_CONFIG.BASE_URL}/api/ksx`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'Authorization': `Bearer ${localStorage.getItem('token')}`
        },
        credentials: 'include',

        body: JSON.stringify({

        }),
      });

      if (response.status === 403) {

        setShowLoginModal(true);
        return;
        // throw new Error('获取用户信息失败');
      }
      const data = await response.json();
      if (data.url) {
        // 安全的URL处理
        const fullUrl = new URL(data.url, window.location.origin).href;
        window.open(fullUrl, '_blank');
      } else {
        console.error('未收到有效URL');
        alert('请先报名');
      }
    } catch (error) {
      console.error('接口调用失败:', error);
      alert('请先报名');
    }
  };

  const handleNavClick = (href: string) => {
    // 处理报名锚点点击
    if (href === "/#consultation-section") {
      if (pathname === "/") {
        // 如果在首页，直接滚动到锚点
        const section = document.getElementById("consultation-section");
        if (section) {
          section.scrollIntoView({ behavior: "smooth" });
        }
      } else {
        // 如果不在首页，先导航到首页再滚动
        router.push("/#consultation-section");
      }
      return false; // 阻止默认链接行为
    }
    return true;
  };
  const redirectToLogin = () => {
    setShowLoginModal(false);
    router.push('/login');
  };
  return (
      <header className="relative z-10">
        {/* 登录提示弹窗 */}
        {showLoginModal && (
            <div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50">
              <div className="bg-white rounded-lg p-6 max-w-md w-full relative">
                {/* Close button */}
                <button
                    onClick={() => setShowLoginModal(false)}
                    className="absolute top-2 right-2 p-1 rounded-full hover:bg-gray-100"
                >
                  <svg
                      xmlns="http://www.w3.org/2000/svg"
                      className="h-6 w-6 text-gray-500"
                      fill="none"
                      viewBox="0 0 24 24"
                      stroke="currentColor"
                  >
                    <path
                        strokeLinecap="round"
                        strokeLinejoin="round"
                        strokeWidth={2}
                        d="M6 18L18 6M6 6l12 12"
                    />
                  </svg>
                </button>

                <p className="mb-6 text-center">已过期请重新登录</p >

                <div className="flex justify-center">
                  <button
                      onClick={redirectToLogin}
                      className="px-4 py-2 bg-blue-600 text-white rounded hover:bg-blue-700"
                  >
                    去登录
                  </button>
                </div>
              </div>
            </div>
        )}
        {/* 顶部深蓝色背景区域 */}
        <div className="bg-red-800 border-b to-blue-800 text-white">
          <div className="container mx-auto px-4">
            <div className="flex items-center justify-between h-16">
              {/* 左侧内容：Logo 和网站名称 */}
              <Link href="/" className="flex items-center space-x-2">
                <div className="relative w-10 h-10 rounded-full bg-white">
                  <Image
                      src="https://hebbkx1anhila5yf.public.blob.vercel-storage.com/IMG_1736.PNG-Tli6okGGMLEMcfkjJVvsoULiHrIE1t.png"
                      alt="网络主播合规网"
                      fill
                      className="object-contain"
                  />
                </div>
                <div className="flex flex-col">
                  <div className="border-b border-white white-border-bottom">
                    <span className="text-xl font-semibold">网络主播合规网</span>
                  </div>
                  <span className="text-sm font-normal">（www.中税师.中国）</span>
                </div>
              </Link>

              {/* 右侧内容：登录和注册按钮 */}
              <div className="flex items-center space-x-4">
                <div
                    className="text-center md:text-left cursor-pointer w-full max-w-xl mx-left"
                    onClick={handleClick}
                >
                  学生登录
                </div>
                <div
                    className="text-center md:text-left cursor-pointer w-full max-w-xl mx-left"
                    onClick={handleClick1}
                >
                  老师登录
                </div>

              </div>
            </div>
          </div>
        </div>

        <div className="bg-red-700 border-b">
          <div className="container mx-auto px-2">
            <nav className="flex justify-center">
              {navItems.map(({ href, label, requiresPost }) => {
                if (pathname.includes("teaquery") || pathname.includes("stuquery") || pathname.includes("tealogin")) {
                  return null;
                }
                return (
                  <Link
                    key={href}
                    href={href}
                    onClick={(e) => {
                      if (requiresPost) {
                        e.preventDefault();
                        const apiPath = href.includes("consultation")
                          ? "demo"
                          : "course-entry";
                        handlePostRequest(apiPath);
                      } else {
                        if (!handleNavClick(href)) {
                          e.preventDefault();
                        }
                      }
                    }}
                    className={`px-4 py-4 text-center border-b-2 transition-colors ${
                      pathname === href || (href === "/#consultation-section" && pathname === "/")
                        ? "border-white text-white font-medium"
                        : "border-transparent text-white hover:text-white/80 hover:border-white/10"
                    }`}
                  >
                    {label}
                  </Link>
                );
              })}
            </nav>
          </div>
        </div>

      </header>
  );
}